package cc.messcat.web.fupin;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.common.util.BeanUtil;
import cc.messcat.common.util.LogUtil;
import cc.messcat.common.util.StringUtil;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.fupin.*;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.system.*;
import cc.messcat.log.OperationLog;
import cc.messcat.service.area.AreaService;
import cc.messcat.service.fupin.*;
import cc.messcat.service.helppeson.HelppesonService;
import cc.messcat.service.helpunits.HelpunitsService;
import cc.messcat.service.system.PermissionService;
import cc.messcat.service.system.UserService;
import cc.messcat.util.Collections;
import cc.messcat.util.ImageHelper;
import cc.messcat.util.QRCodeUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/poorFa")
public class PoorFamilyController {
    private static Logger log = LoggerFactory.getLogger(PoorFamilyController.class);

    @Autowired
    private PoorFamilyService poorFamilyService;

    @Autowired
    private FamilyService familyService;

    @Autowired
    private HelpunitsService helpunitsService;

    @Autowired
    private PreventPovertyService preventPovertyService;

    @Autowired
    @Qualifier("areaServiceImpl")
    private AreaService areaService;
    @Autowired
    public UserService userService;

    @Autowired
    public HelppesonService helppesonService;

    @Autowired
    public RidPoorService ridPoorService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private CacheManager manager;

    @Autowired
    private TableMaintenance tableMaintenance;
    
    @Autowired
	private VisitRecdService visitRecdService;

    //贫困户图片资料上传路径
    @Value("#{ configProperties['upload.image.path'] }")
    private String imgPath;

    /**
     * 贫困户列表查询
     *
     * @throws Exception
     */
//	@OperationLog(desc = "贫困户列表查询", module = "扶贫对象管理")
    @RequestMapping("/queryPoorFamily")
    @ResponseBody
    @SuppressWarnings("all")
    public Object queryPoorFamily(Integer pageNo, Integer pageSize, @Valid PoorFamily poorFamily, String cty,
                                  String cry, HttpServletRequest request, HttpSession session) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        // 兼容操作
        if (BeanUtil.isValid(cty))
            poorFamily.setCounty(cty);
        if (BeanUtil.isValid(cry))
            poorFamily.setCountry(cry);

        //页面按钮授权
        McUser user = (McUser) request.getSession().getAttribute("user");
        Permission poorFamilyManagementPermission = permissionService.getPermissionByURI("povertyStrickenMng");
        List<String> buttonPermissionList = new ArrayList<>();
        for (Role e : userService.retrieveObject(user.getId()).getRoles()) {
            for (Permission p : e.getPermissions()) {
                if (p.getPermissionId() == poorFamilyManagementPermission.getId() && p.getName().contains("button-"))
                    buttonPermissionList.add(p.getName());
            }
        }
        String year = request.getParameter("year");
        String name = request.getParameter("name");
        String idNumber = request.getParameter("idNumber");
        String relation = request.getParameter("relation");
        Pager pager = this.poorFamilyService.getPHPager(pageNo, pageSize, poorFamily, year, name, idNumber, "",
                user);
        //查询帮扶日志数量
        List<PoorFamily> resultList = pager.getResultList();
        for (PoorFamily pf : resultList) {
        	//查询贫困户的帮扶日志
        	Long count = visitRecdService.getCountByPid(pf.getId());
			pf.setVisitingRecordCount(count);
		}
        
        Map result = Collections.generateHashMap(new Object[]{"pageCount", "pageNo", "pageSize", "pageSizeList", "rowCount", "resultList", "buttonPermissionList"},
                new Object[]{pager.getPageCount(), pager.getPageNo(), pager.getPageSize(), pager.getPageSizeList(), pager.getRowCount(), pager.getResultList(), buttonPermissionList});
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, result);
    }

    /**
     * 家庭成员查询
     */
    @OperationLog(desc = "家庭成员查询", module = "扶贫对象管理")
    @RequestMapping("/queryFamily")
    @ResponseBody
    public Object queryFamily(Long fid) {
        List<Family> familyList = this.familyService.queryFaAll();
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, familyList);
    }

    /**
     * 贫困户添加
     */
    @OperationLog(desc = "贫困户添加", module = "扶贫对象管理")
    @RequestMapping("/addPoorFamily")
    @ResponseBody
    public Object addPoorFamily(@Valid PoorFamily poorFamily,
                                @RequestParam(name = "familys", required = false) String familys,
                                @RequestParam(name = "persons", required = false) Long[] persons, HttpServletRequest request, HttpSession session) {

        //户编号重复校验
        if (StringUtils.isNotBlank(poorFamily.getNumber())) {
            List<PoorFamily> persistPoorFamily = poorFamilyService.getPoorFamilyByNumber(poorFamily.getNumber());
            if (!Collections.isEmpty(persistPoorFamily))
                return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "户编号重复");
        }
        String annual = ApplicationProperties.getAnnual();

        poorFamily.setIsDel("0");
        poorFamily.setAnnual(annual);
        poorFamily.setAddTime(new Date());

        //家庭成员json解析
        List<Family> families = null;
        try {
            families = JSON.parseObject(familys, new TypeReference<ArrayList<Family>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.FAIL_CODE_400, "家庭成员参数格式错误");
        }

        int householder = 0;
        String householderName= "";
        for (Family f : families) {
            if ("户主".equals(f.getRelation())) {
                householder++;
                householderName = f.getName();
            }
            if (householder > 1) return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能添加多个户主");
        }

        List<PreventPoverty> preventPovertyList = new ArrayList<>();
        for (Family f : families) {
            f.setAddTime(new Date());
            f.setIsDel("0");
            f.setState("1");
            f.setAnnual(ApplicationProperties.getAnnual());

            familyService.addFamily(f);

            //防贫预警判断
            if(StringUtils.isNotBlank(f.getPreventType())) {
                PreventPoverty preventPoverty =
                        new PreventPoverty(new Date(),new Date(),null,f.getId(),poorFamily.getCountry(),poorFamily.getVillage(),f.getPreventType(),householderName,f.getName(),f.getLastSelfExpense());
                preventPovertyList.add(preventPoverty);
            }
        }
        poorFamily.setFamily(families);

        Area area = areaService.getAreaByName(poorFamily.getCountry(), poorFamily.getVillage());
        poorFamily.setArea(area);

        if (persons != null && persons.length > 0) {
            List<HelpPerson> hps = helppesonService.listHelpPerson(Arrays.toString(persons).replaceAll("[\\[\\]]", ""));
            poorFamily.setHelpPersons(hps);
        }

        Long id = poorFamilyService.addPoorFamily(poorFamily);

        //保存防贫预警
        for (PreventPoverty e : preventPovertyList) {
            e.setPoorFamilyID(id);
            preventPovertyService.addObject(e);
        }

        RidPoor ridPoor = new RidPoor();
        ridPoor.setAddTime(new Date());
        ridPoor.setAnnual(ApplicationProperties.getAnnual());
        ridPoor.setOriginPoorFamily(poorFamily);

        //贫困户变更历史
        PoorFamilyHistory poorFamilyHistory = generatePoorFamilyHistory(poorFamily);
        poorFamilyService.addPoorFamilyHistofy(poorFamilyHistory);
        //家庭成员变更历史
        List<FamilyHistory> familyHistorys = new ArrayList<>();
        for (Family f : poorFamily.getFamily()) {
            FamilyHistory familyHistory = generateFamilyHistory(f);
            familyHistory.setFid(poorFamilyHistory.getId());
            familyHistorys.add(familyHistory);
            familyService.addFamilyHistory(familyHistory);
        }
        poorFamilyHistory.setFamilyHistories(familyHistorys);
        ridPoor.setPoorFamilyHistory(poorFamilyHistory);
        // 8为新识别贫困户
        ridPoor.setChanges("8");
        ridPoorService.addObject(ridPoor);

        //贫困村记录中的贫困户与贫困人口数维护
        tableMaintenance.updatePoorFamilyCount(annual, area.getId());
        tableMaintenance.updateFamilyCount(annual, area.getId());

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS, id);
    }

    /**
     * 新增贫困户时的家庭成员添加
     */
    @OperationLog(desc = "家庭成员添加", module = "扶贫对象管理")
    @RequestMapping("/addFamily")
    @ResponseBody
    @Deprecated
    public Object addFamily(HttpServletRequest request, @Valid Family family, HttpSession session) {
        family.setAddTime(new Date());
        family.setIsDel("0");
        family.setState("0");
        family.setAnnual(ApplicationProperties.getAnnual());
        String relation = request.getParameter("relation");
        String fid = request.getParameter("fid");
        List<Family> families = familyService.queryFaAll2();
        if ("户主".equals(relation) && fid == null) {
            for (int i = 0; i < families.size(); i++) {
                if (families.get(i).getFid() == null && families.get(i).getRelation().equals("户主")) {

                    return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能重复添加户主");
                } else if (families.get(i).getFid() == null && fid == null && families.get(i).getRelation().equals("户主")) {
                    return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能重复添加户主");
                } else if (families.get(i).getFid() == null && fid == null && relation.equals("户主")) {
                    return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能重复添加户主");
                } else if (fid == null && relation.equals("户主")) {
                    return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能重复添加户主");
                }
            }
        }
        family.setId(this.familyService.addFamily(family));
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS);
    }

    /**
     * 贫困户编辑时的家庭成员修改和添加
     */
    @OperationLog(desc = "家庭成员修改或添加", module = "扶贫对象管理")
    @RequestMapping("/addOrUpdateFamily")
    @ResponseBody
    @Deprecated
    public Object addOrUpdateFamily(@Valid Family family, HttpServletRequest request, HttpSession session) {
        if (family.getFid() == null) {
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "该家庭成员没有所属贫困户");
        }

        String annual = ApplicationProperties.getAnnual();
        String relation = family.getRelation();

        //查出户主
        List<Family> fy = familyService.queryFamilyByFid(family.getFid());
        PoorFamily persistentPoorFamily = poorFamilyService.get(family.getFid());
        PoorFamilyHistory poorFamilyHistory = generatePoorFamilyHistory(persistentPoorFamily);

        List<FamilyHistory> familyHistories = new ArrayList<>();
        for (Family f : persistentPoorFamily.getFamily()) {
            FamilyHistory familyHistory = generateFamilyHistory(f);
            familyHistory.setFid(poorFamilyHistory.getId());
            familyService.addFamilyHistory(familyHistory);
            familyHistories.add(familyHistory);
        }

        poorFamilyHistory.setFamilyHistories(familyHistories);
        poorFamilyService.addPoorFamilyHistofy(poorFamilyHistory);

        RidPoor ridPoor = new RidPoor();
        ridPoor.setAddTime(new Date());
        ridPoor.setAnnual(annual);
        ridPoor.setOriginPoorFamily(persistentPoorFamily);
        ridPoor.setPoorFamilyHistory(poorFamilyHistory);

        //新增family
        if (family.getId() == null) {
            if (!Collections.isEmpty(fy) && "户主".equals(relation)) {
                return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能重复添加户主");
            }

            family.setAddTime(new Date());
            family.setAnnual(persistentPoorFamily.getAnnual());
            family.setIsDel("0");
            family.setState("1");
            familyService.addFamily(family);

            //3为家庭成员增加
            ridPoor.setChanges("3");
            ridPoorService.addObject(ridPoor);

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS);
        }

        //修改family
        Family persistentFamily = familyService.retrieveObject(family.getId());
        if (!Collections.isEmpty(fy) && "户主".equals(relation) && !"户主".equals(persistentFamily.getRelation())) {
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能重复添加户主");
        }
        family.setAddTime(persistentFamily.getAddTime());
        family.setState("1");
        family.setAnnual(persistentFamily.getAnnual());
        family.setIsDel("0");

        //6为户主变更, 2为家庭成员信息变更
        ridPoor.setChanges("户主".equals(persistentFamily.getRelation()) || relation.equals("户主") ? "6" : "2");
        ridPoorService.addObject(ridPoor);

        family.setUpTime(new Date());
        BeanUtils.copyProperties(family, persistentFamily);
        familyService.modifyObject(persistentFamily);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS);
    }

    /**
     * 贫困户修改
     *
     * @throws Exception
     */
    @OperationLog(desc = "贫困户修改", module = "扶贫对象管理")
    @RequestMapping("/updatePoorFamily")
    @ResponseBody
    public Object updatePoorFamily(@Valid PoorFamily poorFamily, String familys, String persons, HttpServletRequest request, HttpSession session) throws Exception {
        //户编号重复校验
        if (StringUtils.isNotBlank(poorFamily.getNumber())) {
            List<PoorFamily> persistPoorFamily = poorFamilyService.getPoorFamilyByNumber(poorFamily.getNumber());
            for (PoorFamily e : persistPoorFamily) {
                if (!e.getId().equals(poorFamily.getId()))
                    return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "户编号重复");
            }
        }

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        String annual = ApplicationProperties.getAnnual();
        Area newArea = areaService.getAreaByName(poorFamily.getCountry(), poorFamily.getVillage());

        PoorFamily persistentPoorFamily = poorFamilyService.get(poorFamily.getId());
        Area oldArea = areaService.getByAreaID(persistentPoorFamily.getArea().getId());
        PoorFamilyHistory poorFamilyHistory = generatePoorFamilyHistory(persistentPoorFamily);
        poorFamilyService.addPoorFamilyHistofy(poorFamilyHistory);

        List<FamilyHistory> familyHistories = new ArrayList<>();
        List<Long> oldPreventFamilyID = preventPovertyService.getFamilyIDByPoorFamilyID(poorFamily.getId());
        for (Family f : persistentPoorFamily.getFamily()) {
            FamilyHistory familyHistory = generateFamilyHistory(f);
            familyHistory.setFid(poorFamilyHistory.getId());
            familyService.addFamilyHistory(familyHistory);
            familyHistories.add(familyHistory);
        }

        List<Family> families;
        try {
            families = JSON.parseObject(familys, new TypeReference<ArrayList<Family>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.FAIL_CODE_400, "家庭成员参数格式错误");
        }

        int householder = 0;
        String householderName = "";
        for (Family f : families) {
            if ("户主".equals(f.getRelation())) {
                householder++;
                householderName = f.getName();
            }
            if (householder > 1) return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "不能添加多个户主");
        }

        //从页面提交的被修改的familyid
        List<Long> familyIDs = new ArrayList<>();
        List<Family> preventPovertyFamilyList = new ArrayList<>();
        for (Family f : families) {
            //防贫预警
            if(StringUtils.isNotBlank(f.getPreventType())) {preventPovertyFamilyList.add(f);}

            if (f.getId() != null) {
                familyIDs.add(f.getId());
                f.setUpTime(new Date());
                f.setIsDel("0");
                f.setState("1");
                f.setFid(poorFamily.getId());
                familyService.merge(f);
                continue;
            }
            f.setAddTime(new Date());
            f.setIsDel("0");
            f.setState("1");
            f.setFid(poorFamily.getId());
            f.setAnnual(ApplicationProperties.getAnnual());
            familyService.addFamily(f);
        }

        for (Family f : persistentPoorFamily.getFamily()) {
            //筛选未从页面传回的family id,代表是被删除的记录
            if (!familyIDs.contains(f.getId())) {
                f.setUpTime(new Date());
                f.setIsDel("1");
                families.add(f);
            }
        }

        preventPovertyService.complexMaintainPreventPoverty(poorFamily.getCountry(),poorFamily.getVillage(),householderName,preventPovertyFamilyList,oldPreventFamilyID);
        poorFamily.setFamily(families);

        if (StringUtils.isNotBlank(persons) && persons.matches("([0-9 ,])+")) {
            List<HelpPerson> helpPerson = helppesonService.listHelpPerson(persons);
            poorFamily.setHelpPersons(helpPerson);
        }

        //设置回不变更的旧数据
        poorFamily.setAnnual(persistentPoorFamily.getAnnual());
        poorFamily.setArea(newArea);
        poorFamily.setIsDel("0");
        poorFamily.setAddTime(persistentPoorFamily.getAddTime());
        poorFamily.setUpTime(new Date());

        //照片资料修改
        updatePoorFamilyImgs(persistentPoorFamily, poorFamily);

        BeanUtils.copyProperties(poorFamily, persistentPoorFamily);

        RidPoor ridPoor = new RidPoor();
        ridPoor.setAddTime(new Date());
        ridPoor.setAnnual(annual);
        if (families.size() > familyHistories.size()) {
            //3为家庭成员增加
            ridPoor.setChanges("3");
        }
        if (families.size() < familyHistories.size()) {
            // 4为家庭成员减少
            ridPoor.setChanges("4");
        }
        ridPoor.setChanges("5");//5为户基本信息变更
        //家庭成员变更历史
        poorFamilyHistory.setFamilyHistories(familyHistories);
        ridPoor.setOriginPoorFamily(persistentPoorFamily);
        ridPoor.setPoorFamilyHistory(poorFamilyHistory);
        this.ridPoorService.addObject(ridPoor);

        //贫困村记录中的贫困户与贫困人口数维护
        tableMaintenance.updatePoorFamilyCount(annual, oldArea.getId());
        tableMaintenance.updateFamilyCount(annual, oldArea.getId());
        tableMaintenance.updatePoorFamilyCount(annual, newArea.getId());
        tableMaintenance.updateFamilyCount(annual, newArea.getId());

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS);
    }

    /**
     * 贫困户删除
     */
    @OperationLog(desc = "贫困户删除", module = "扶贫对象管理")
    @RequestMapping("/deletePoorFamily")
    @ResponseBody
    public Object deletePoorFamily(Long id, HttpSession session) {
        PoorFamily poorFamily = this.poorFamilyService.get(id);

        String annual = ApplicationProperties.getAnnual();
        Area area = poorFamily.getArea();

        RidPoor ridPoor = new RidPoor();
        ridPoor.setAddTime(new Date());
        ridPoor.setAnnual(ApplicationProperties.getAnnual());
        ridPoor.setReTime(new Date());
        ridPoor.setOriginPoorFamily(poorFamily);
        PoorFamilyHistory poorFamilyHistory = generatePoorFamilyHistory(poorFamily);
        //家庭成员历史
        List<FamilyHistory> familyHistories = new ArrayList<>();
        for (Family f : poorFamily.getFamily()) {
            FamilyHistory familyHistory = generateFamilyHistory(f);
            familyHistory.setFid(poorFamilyHistory.getId());
            familyService.addFamilyHistory(familyHistory);
            familyHistories.add(familyHistory);
        }
        poorFamilyHistory.setFamilyHistories(familyHistories);
        poorFamilyService.addPoorFamilyHistofy(poorFamilyHistory);
        ridPoor.setPoorFamilyHistory(poorFamilyHistory);
        ridPoor.setChanges("10");// 注销
        this.ridPoorService.addObject(ridPoor);

        for (Family f : poorFamily.getFamily()) {
            f.setIsDel("1");
            this.familyService.modifyObject(f);
        }
        poorFamily.setIsDel("1");

        this.poorFamilyService.modifyObject(poorFamily);

        //贫困村记录中的贫困户与贫困人口数维护
        tableMaintenance.updatePoorFamilyCount(annual, area.getId());
        tableMaintenance.updateFamilyCount(annual, area.getId());

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS);
    }

    /**
     * 清除新增页面的家庭成员
     */
    @RequestMapping("/deleteFamily")
    @ResponseBody
    @Deprecated
    public Object deleteFamily() {
//		List<Family> list = this.familyService.queryFaAll();
//		for (int i = 0; i < list.size(); i++) {
//			Family family = this.familyService.retrieveObject(list.get(i).getId());
//			family.setIsDel("0");
//			this.familyService.modifyObject(family);
//		}
        return new ResponseBean(CommonConstant.FAIL_CODE_400, "该操作不被支持");
    }


    /**
     * 删除新增页面的家庭成员
     */
    @RequestMapping("/deleteFamilyFid")
    @ResponseBody
    @Deprecated
    public Object deleteFamilyFid() {
//		List<Family> list = this.familyService.queryFaAllid();
//		for (int i = 0; i < list.size(); i++) {
//			Family family = this.familyService.retrieveObject(list.get(i).getId());
//			this.familyService.removeObject(family);
//		}
        return new ResponseBean(CommonConstant.FAIL_CODE_400, "该操作不被支持");
    }

    /**
     * 家庭成员根据id删除
     */
    @OperationLog(desc = "家庭成员删除", module = "扶贫对象管理")
    @RequestMapping("/deleteFamilyid")
    @ResponseBody
    @Deprecated
    public Object deleteFamilyid(String sid, HttpServletRequest request, HttpSession session) {
        String[] spli = sid.split(",");
        String aa = spli[0];
        Family family2 = familyService.get(Long.valueOf(aa));

        if (family2.getFid() == null) {
            for (String id : spli) {
                Family family3 = familyService.retrieveObject(Long.valueOf(id));
                familyService.removeObject(family3);
            }
            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS);
        }

        RidPoor ridPoor = new RidPoor();
        ridPoor.setAddTime(new Date());
        ridPoor.setAnnual(ApplicationProperties.getAnnual());
        ridPoor.setChanges("4");// 4为家庭成员减少
        PoorFamily poorFamily = poorFamilyService.get(family2.getFid());
        PoorFamilyHistory poorFamilyHistory = generatePoorFamilyHistory(poorFamily);
        poorFamilyService.addPoorFamilyHistofy(poorFamilyHistory);
        List<FamilyHistory> familyHistories = new ArrayList<>();
        for (Family f : poorFamily.getFamily()) {
            FamilyHistory familyHistory = generateFamilyHistory(f);
            familyHistory.setFid(poorFamilyHistory.getId());
            familyService.addFamilyHistory(familyHistory);
            familyHistories.add(familyHistory);
        }
        poorFamilyHistory.setFamilyHistories(familyHistories);
        ridPoor.setOriginPoorFamily(poorFamily);
        ridPoor.setPoorFamilyHistory(poorFamilyHistory);

        for (String id : spli) {
            Family family3 = familyService.retrieveObject(Long.valueOf(id));
            family3.setIsDel("1");
            familyService.modifyObject(family3);
        }
        this.ridPoorService.addObject(ridPoor);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS);
    }

    /**
     * 贫困户查看详情（根据ID）
     *
     * @return
     */
    @SuppressWarnings("all")
    @OperationLog(desc = "查询贫困户详情", module = "扶贫对象管理")
    @RequestMapping("/getPoorFamily")
    @ResponseBody
    public Object getPoorFamily(Long id, HttpSession session) {

        McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        PoorFamily poorFamily = this.poorFamilyService.get(id);
        List<HelpPerson> helpPerson = new ArrayList<>();
        List<Family> family = new ArrayList<>();
        if (poorFamily != null) {
            Iterator<HelpPerson> it = poorFamily.getHelpPersons().iterator();
            while (it.hasNext()) {
                HelpPerson next = it.next();
                if ("1".equalsIgnoreCase(next.getStatus())) helpPerson.add(next);
            }
            Iterator<Family> it2 = poorFamily.getFamily().iterator();
            while (it2.hasNext()) {
                Family next = it2.next();
                if ("0".equalsIgnoreCase(next.getIsDel())) family.add(next);
            }
        }

        PoorFamily viewPoorFamily = new PoorFamily();
        BeanUtils.copyProperties(poorFamily, viewPoorFamily);
        viewPoorFamily.setFamily(family);
        viewPoorFamily.setHelpPersons(helpPerson);

        Map map = new HashMap<>();
        map.put("poorFamily", viewPoorFamily);

        Map<String, Object> fieldPermission = new HashMap<>();

        Permission poorFamilyManagementPermission = permissionService.getPermissionByURI("povertyStrickenMng");
        if (poorFamilyManagementPermission != null) {
            for (Role r : user.getRoles()) {
                for (Permission e : r.getPermissions()) {
                    if (e.getPermissionId() == poorFamilyManagementPermission.getId()) {
                        fieldPermission.put(e.getName(), true);
                    }
                }
            }
        }
        map.put("fieldPermission", fieldPermission);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, map);
    }

    public Object updatePoorFamily(PoorFamily poorFamily) {
        if (poorFamily != null) {

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, null);
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_300, CommonConstant.MSG_UPDATE_FAIL, null);
    }

    /**
     * 贫困户导入
     *
     * @param file
     * @param session
     * @return
     */
    @OperationLog(desc = "贫困户导入", module = "扶贫对象管理")
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public Object addPoorFamilyExc(String file, HttpSession session) {
        long dataTimeStr = System.currentTimeMillis();
        try {
            McUser mcUser = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            // 开始导入
            String result = this.poorFamilyService.adduploadFile(file, session, mcUser);
            long dataTimeEnd = System.currentTimeMillis();
            System.out.println(dataTimeEnd - dataTimeStr + "S>>>>>>贫困户总耗时Cont");
            log.info(dataTimeEnd - dataTimeStr + "S>>>>>>贫困户总耗时Cont");
            // 路径
            if ("NO_URL".equals(result)) {
                return new ResponseBean(CommonConstant.FAIL_CODE_400, CommonConstant.MSG_FILE_NOURL);
            }
            // 导入错误
            if (!"T".equals(result)) {
                return new ResponseBean(CommonConstant.SUCCESS_CODE_300, CommonConstant.MSG_IMPORT_ERROR, result);
            }

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_IMPORT_SUCCESS);

        } catch (Exception e) {
            LogUtil.logException("PoorFamilyController import has exception:", e);
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_IMPORT_ERROR);
        }
    }

    /**
     * 结对查询
     *
     * @return
     */
    @OperationLog(desc = "结对查询", module = "帐表查询")
    @RequestMapping("/getPoorFamilys")
    @ResponseBody
    public Object getPoorFamilys(@Valid PoorFamily poorFamily, Integer pageNo, Integer pageSize, String name,
                                 String idNumber, String Whether, String year, HttpServletRequest request) {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        year = StringUtils.isBlank(year) ? ApplicationProperties.getAnnual() : year;

        McUser user = (McUser) request.getSession().getAttribute("user");
        Pager pager = this.poorFamilyService.getPager(poorFamily, pageNo, pageSize, name, idNumber, Whether, year, user);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 结对查询导出
     */
    @OperationLog(desc = "结对查询导出", module = "帐表导出")
    @RequestMapping("/exportPoorFamilys")
    @ResponseBody
    public Object exportPoorFamilys(@Valid PoorFamily poorFamily, String name, String idNumber, HttpSession session,
                                    String Whether, String year, HttpServletResponse response) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            year = StringUtils.isBlank(year) ? ApplicationProperties.getAnnual() : year;
            HSSFWorkbook wb = poorFamilyService.exportPoorFamilys(poorFamily, name, idNumber, Whether, year, user);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("结对查询导出", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 根据id查出结对信息
     *
     * @return
     */
//	@OperationLog(desc = "根据id查出结对信息", module = "帐表查询")
    @RequestMapping("/getPoorFamilysid")
    @ResponseBody
    public Object getPoorFamilysid(Long id) {
        List<PoorFamily> poorFamilies = this.poorFamilyService.poorfamilies(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, poorFamilies);
    }

    /**
     * 贫困户模糊查询
     */
//	@OperationLog(desc = "贫困户模糊查询", module = "扶贫对象管理")
    @RequestMapping("/queryPoorHFamily")
    @ResponseBody
    public Object queryPoorHFamily(Integer pageNo, Integer pageSize, @Valid PoorFamily poorFamily, String cty,
                                   String cry, HttpServletRequest request) {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        // 兼容操作
        if (BeanUtil.isValid(cty))
            poorFamily.setCounty(cty);
        if (BeanUtil.isValid(cry))
            poorFamily.setCountry(cry);

        String year = request.getParameter("year");
        String name = request.getParameter("name");
        String idNumber = request.getParameter("idNumber");
        String groupNumber = request.getParameter("groupNumber");
        McUser user = (McUser) request.getSession().getAttribute("user");
        Pager pager = this.poorFamilyService.getPHPager(pageNo, pageSize, poorFamily, year, name, idNumber, groupNumber,
                user);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 贫困户管理导出
     *
     * @throws Exception
     */
    @OperationLog(desc = "贫困户管理导出", module = "扶贫对象管理")
    @RequestMapping("/exportPoorFamily")
    @ResponseBody
    public Object exportPoorFamily(Integer pageNo, Integer pageSize, @Valid PoorFamily poorFamily, String cty,
                                   String cry, HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        // 兼容操作
        if (BeanUtil.isValid(cty))
            poorFamily.setCounty(cty);
        if (BeanUtil.isValid(cry))
            poorFamily.setCountry(cry);

        String year = request.getParameter("year");
        String name = request.getParameter("name");
        String idNumber = request.getParameter("idNumber");
        String relation = request.getParameter("relation");
        McUser user = (McUser) request.getSession().getAttribute("user");

        try {
            HSSFWorkbook wb = poorFamilyService.exportPoorFamily(poorFamily, year, name, idNumber, relation,
                    user);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户管理表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户查询导出
     */
    @OperationLog(desc = "贫困户查询导出", module = "扶贫对象管理")
    @RequestMapping("/exportPoorFamilyZ")
    @ResponseBody
    public Object exportPoorFamilyZ(@Valid PoorFamily poorFamily, HttpServletRequest request,
                                    @RequestParam(name = "year", required = false) String year, HttpSession session,
                                    HttpServletResponse response) {
        McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        String name = request.getParameter("name");
        String idNumber = request.getParameter("idNumber");
        String groupNumber = request.getParameter("groupNumber");
        try {
            HSSFWorkbook wb = poorFamilyService.exportPoorFamilyZ(year, poorFamily, user, name, idNumber, groupNumber);

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("贫困户查询表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }


    /**
     * 首页
     * 贫困户的总户数
     */
//	@OperationLog(desc = "贫困户的总户数", module = "首页统计")
    @RequestMapping("/totalFamily")
    @ResponseBody
    public Object totalFamily(HttpSession session) {
        List pts = new ArrayList<>(0);
        Element element = manager.getCache("indexStatistics").get("totalFamily");
        if (element != null) {
            pts = (List) element.getObjectValue();
        } else {
            pts = poorFamilyService.totalPoor();
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pts);
//		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, new ArrayList<>());
    }

    /**
     * 首页
     * 帮扶单位数
     */
//	@OperationLog(desc = "帮扶单位数", module = "首页统计")
    @RequestMapping("/unitsNumber")
    @ResponseBody
    public Object unitsNumber(HttpSession session) {
        List unitsN = new ArrayList<>(0);
        Element element = manager.getCache("indexStatistics").get("unitsNumber");
        if (element != null) {
            unitsN = (List) element.getObjectValue();
        } else {
            unitsN = helpunitsService.unitsNr();
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, unitsN);
//		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, new ArrayList<>());
    }

    /**
     * 证件号重复查询
     */
    @OperationLog(desc = "证件号重复查询", module = "账表查询")
    @RequestMapping("/queryDuplicateID")
    @ResponseBody
    public Object queryDuplicateID(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                   @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                   @RequestParam(name = "year", required = false) String year,
                                   @RequestParam(name = "country", required = false) String country, HttpSession session) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager pager = poorFamilyService.complexQueryDuplicateID(pageNo, pageSize, year, country, user);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 证件号重复excel导出
     */
    @OperationLog(desc = "证件号重复记录导出", module = "账表查询")
    @RequestMapping("/exportDuplicateID")
    @ResponseBody
    public Object exportDuplicateIDExcel(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                         @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                         @RequestParam(name = "year", required = false) String year,
                                         @RequestParam(name = "country", required = false) String country, HttpSession session,
                                         HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;

        try {
            HSSFWorkbook wb = poorFamilyService.complexExportDuplicateIDExcel(pageNo, pageSize, year, country, user);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("证件号重复记录表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 户主异常查询
     */
    @OperationLog(desc = "户主异常查询", module = "账表查询")
    @RequestMapping("/exceptH")
    @ResponseBody
    public Object queryExceptHouseholder(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                         @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                         @RequestParam(name = "year", required = false) String year,
                                         @RequestParam(name = "country", required = false) String country,
                                         @RequestParam(name = "village", required = false) String village,
                                         @RequestParam(name = "type", required = false) String typeStr, HttpSession session) {

        int type = 0;
        if (StringUtils.isNotBlank(typeStr)) {
            type = "无户主".equals(typeStr.trim()) ? 1 : "多户主".equals(typeStr.trim()) ? 2 : 3;
        }

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager page = poorFamilyService.complexQueryExceptHouseholder(year, country, village, type, pageNo, pageSize, user);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, page);
    }

    /**
     * 首页
     * 根据主要致贫原因统计贫困户
     */
    @ResponseBody
    @RequestMapping(value = "poorCauseStat", method = {RequestMethod.GET})
    public Object poorCauseStat(HttpSession session) {
        List result = new ArrayList<>(0);
        Element element = manager.getCache("indexStatistics").get("poorCauseStat");
        if (element != null) {
            result = (List) element.getObjectValue();
        } else {
            result = poorFamilyService.queryMainPovertyCauses();
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, result);
    }

    /**
     * 户主异常导出
     */
    @OperationLog(desc = "户主异常记录导出", module = "账表查询")
    @RequestMapping("/exportExceptH")
    @ResponseBody
    public Object exportExceptHouseholder(@RequestParam(name = "year", required = false) String year,
                                          @RequestParam(name = "country", required = false) String country,
                                          @RequestParam(name = "village", required = false) String village,
                                          @RequestParam(name = "type", required = false) String typeStr, HttpSession session,
                                          HttpServletResponse response) {

        int type = 0;
        if (StringUtils.isNotBlank(typeStr)) {
            type = "无户主".equals(typeStr.trim()) ? 1 : "多户主".equals(typeStr.trim()) ? 2 : 3;
        }

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {
            HSSFWorkbook wb = poorFamilyService.complexExportExceptHouseholder(year, country, village, type, user);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("户主异常记录表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户学生查询
     *
     * @return
     */
    @OperationLog(desc = "贫困户学生查询", module = "帐表查询")
    @RequestMapping("/poorStudent")
    @ResponseBody
    public Object queryPoorStudent(@Valid Family family,
                                   @RequestParam(name = "pageNo", required = false) Integer pageNo,
                                   @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                   @RequestParam(name = "country", required = false) String country,
                                   @RequestParam(name = "year", required = false) String year, HttpSession session) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager pager = poorFamilyService.complexQueryPoorStudent(year, country, family, pageNo, pageSize, user);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);

    }

    /**
     * 贫困户学生导出
     */
    @OperationLog(desc = "贫困户学生记录导出", module = "帐表查询")
    @RequestMapping("/exportPoorStudent")
    @ResponseBody
    public Object exportPoorStudent(@Valid Family family,
                                    @RequestParam(name = "country", required = false) String country,
                                    @RequestParam(name = "year", required = false) String year, HttpSession session,
                                    HttpServletResponse response) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {
            HSSFWorkbook wb = poorFamilyService.complexExportPoorStudent(year, country, family, user);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户学生记录表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困人口劳动能力类型统计
     *
     * @return
     */
    @OperationLog(desc = "贫困人口劳动能力类型统计 ", module = "统计分析")
    @RequestMapping("/laborTypeStatistics")
    @ResponseBody
    public Object laborTypeStatistics(@RequestParam(name = "pageSize", required = false) Integer pageSize,
                                      @RequestParam(name = "pageNo", required = false) Integer pageNo,
                                      @RequestParam(name = "year", required = false) String year,
                                      @RequestParam(name = "country", required = false) String country,
                                      @RequestParam(name = "village", required = false) String village,
                                      @RequestParam(name = "poverty", required = false) String poverty, HttpSession session,
                                      HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager page = familyService.laborTypeStatistics(user, pageNo, pageSize, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, page);
    }

    /**
     * 贫困人口劳动能力类型统计导出
     *
     * @return
     */
    @OperationLog(desc = "贫困人口劳动能力类型统计excel导出 ", module = "统计分析")
    @RequestMapping("/exportLaborTypeStatistics")
    @ResponseBody
    public Object exportLaborTypeStatistics(@RequestParam(name = "year", required = false) String year,
                                            @RequestParam(name = "country", required = false) String country,
                                            @RequestParam(name = "village", required = false) String village,
                                            @RequestParam(name = "poverty", required = false) String poverty, HttpSession session,
                                            HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {
            HSSFWorkbook wb = familyService.exportLaborTypeStatistics(user, null, null, year, country, village,
                    poverty);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口劳动能力类型统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困人口基本信息统计(根据镇和年度查询,其中如果不选镇的话就以镇为单位查询，选镇的就以该镇下的村为单位查询)
     */
    @OperationLog(desc = "贫困人口基本信息统计 ", module = "统计分析")
    @ResponseBody
    @RequestMapping(value = "queryPoorPeople", method = RequestMethod.POST)
    public Object queryPoorPeople(HttpSession session, Integer pageNo, Integer pageSize, String year, String town,
                                  String poverty) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryPoorPeople(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 导出贫困人口的基本信息
     *
     * @param year
     * @param town
     * @throws IOException
     */
    @OperationLog(desc = "贫困人口基本信息统计excel导出 ", module = "统计分析")
    @RequestMapping(value = "exportPoorPeople")
    public Object exportPoorPeople(HttpSession session, HttpServletResponse response, String year, String town,
                                   String poverty) {
        try {

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口基本信息统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            HSSFWorkbook wb = poorFamilyService.exportPoorPeople(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困人口年龄分组情况统计表
     */
    @OperationLog(desc = "贫困人口年龄分组情况统计", module = "统计分析")
    @SuppressWarnings({"unused", "rawtypes"})
    @ResponseBody
    @RequestMapping(value = "queryAgeGroup")
    public Object queryAgeGroup(HttpSession session, Integer pageNo, Integer pageSize, String year, String town,
                                String poverty) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryAgeGroup(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 用execl导出贫困人口年龄分组情况
     */
    @ResponseBody
    @OperationLog(desc = "贫困人口年龄分组情况统计excel导出", module = "统计分析")
    @RequestMapping(value = "exportAgeGroup")
    public Object exportAgeGroup(HttpSession session, HttpServletResponse response, String year, String town,
                                 String poverty) {
        try {
            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口年龄分组情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            HSSFWorkbook wb = poorFamilyService.exportAgeGroup(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }


    /**
     * 贫困人口务工状况统计表
     *
     * @param session
     * @param pageNo
     * @param pageSize
     * @param year
     * @param town
     * @param poverty
     * @return
     */
    @ResponseBody
    @OperationLog(desc = "贫困人口务工状况统计", module = "统计分析")
    @RequestMapping(value = "queryWorkState")
    public Object queryWorkState(HttpSession session, Integer pageNo, Integer pageSize, String year, String town, String poverty) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryWorkState(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 贫困人口务工状况统计表execl导出
     */
    @ResponseBody
    @OperationLog(desc = "贫困人口务工状况统计execl导出", module = "统计分析")
    @RequestMapping(value = "exportWorkState")
    public Object exportWorkState(HttpSession session, HttpServletResponse response, String year, String town,
                                  String poverty) {
        try {
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口务工状况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            HSSFWorkbook wb = poorFamilyService.exportWorkState(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }


    /**
     * 贫困人口务工时间情况统计表
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @OperationLog(desc = "贫困人口务工时间情况统计", module = "统计分析")
    @RequestMapping(value = "queryWorkTime")
    public Object queryWorkTime(HttpSession session, Integer pageNo, Integer pageSize, String year, String town,
                                String poverty) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryWorkTime(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 贫困人口务工时间情况execl导出
     */
    @ResponseBody
    @RequestMapping(value = "exportWorkTime")
    @OperationLog(desc = "贫困人口务工时间情况统计execl导出", module = "统计分析")
    public Object exportWorkTime(HttpSession session, HttpServletResponse response, String year, String town,
                                 String poverty) {
        try {
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口务工时间情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            HSSFWorkbook wb = poorFamilyService.exportWorkTime(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困人口在校生情况统计表
     */
    @ResponseBody
    @RequestMapping(value = "queryInternalStudent")
    @OperationLog(desc = "贫困人口在校生情况统计", module = "统计分析")
    public Object queryInternalStudent(HttpSession session, Integer pageNo, Integer pageSize, String year, String town,
                                       String poverty) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryInternalStudent(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 导出贫困人口在校生情况统计表
     */
    @ResponseBody
    @RequestMapping(value = "exportInternalStudent")
    @OperationLog(desc = "贫困人口在校生情况统计excel导出", module = "统计分析")
    public Object exportInternalStudent(HttpSession session, HttpServletResponse response, String year, String town,
                                        String poverty) {
        try {
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口在校生情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            HSSFWorkbook wb = poorFamilyService.exportInternalStudent(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户贫困人数统计表
     *
     * @return
     */
    @ResponseBody
    @OperationLog(desc = "贫困户贫困人数统计", module = "统计分析")
    @RequestMapping(value = "queryPoorStatus")
    public Object queryPoorStatus(HttpSession session, Integer pageNo, Integer pageSize, String year, String town,
                                  String poverty) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryPoorStatus(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 导出贫困户贫困人数统计表
     */
    @ResponseBody
    @RequestMapping(value = "exportPoorStatus")
    @OperationLog(desc = "贫困户贫困人数统计excel导出", module = "统计分析")
    public Object exportPoorStatus(HttpSession session, HttpServletResponse response, String year, String town,
                                   String poverty) {
        try {
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户贫困人数统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            HSSFWorkbook wb = poorFamilyService.exportPoorStatus(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户主要致贫原因情况统计
     *
     * @param session
     * @param pageNo
     * @param pageSize
     * @param year
     * @param town
     * @param poverty
     * @return
     */
    @ResponseBody
    @OperationLog(desc = "贫困户主要致贫原因情况统计", module = "统计分析")
    @RequestMapping(value = "queryMainPovertyCauses")
    public Object queryMainPovertyCauses(HttpSession session, Integer pageNo, Integer pageSize, String year,
                                         String town, String poverty) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryMainPovertyCauses(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 导出贫困户主要致贫原因的情况
     */
    @ResponseBody
    @OperationLog(desc = "贫困户主要致贫原因情况统计excel导出", module = "统计分析")
    @RequestMapping(value = "exportMainPovertyCauses")
    public Object exportMainPovertyCauses(HttpSession session, HttpServletResponse response, String year, String town,
                                          String poverty) {
        try {
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户主要致贫原因情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            HSSFWorkbook wb = poorFamilyService.exportMainPovertyCauses(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户其他致贫原因的统计
     */
    @ResponseBody
    @OperationLog(desc = "贫困户其他致贫原因的统计", module = "统计分析")
    @RequestMapping(value = "queryOtherPovertyCauses")
    public Object queryOtherPovertyCauses(HttpSession session, Integer pageNo, Integer pageSize, String year,
                                          String town, String poverty) {
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager pager = poorFamilyService.queryOtherPovertyCauses(user, pageNo, pageSize, year, town, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    /**
     * 导出其他贫困户致贫原因
     */
    @ResponseBody
    @OperationLog(desc = "贫困户其他致贫原因统计excel导出", module = "统计分析")
    @RequestMapping(value = "exportOtherPovertyCauses")
    public Object exportOtherPovertyCauses(HttpSession session, HttpServletResponse response, String year, String town,
                                           String poverty) {
        try {
            // 响应设置
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户其他致贫原因情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            McUser user = userService
                    .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
            HSSFWorkbook wb = poorFamilyService.exportOtherPovertyCauses(user, year, town, poverty);

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户根据id查询帮扶负责人
     */
    @RequestMapping("/queryFamilyhelpperson")
    @ResponseBody
    public Object queryFamilyhelpperson(Long id) {
        List<HelpPerson> poorFamilies = this.poorFamilyService.queryFamilyhelpperson(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, poorFamilies);
    }

    /**
     * 贫困户人口规模统计
     *
     * @return
     */
    @OperationLog(desc = "贫困户人口规模统计", module = "统计分析")
    @RequestMapping("/populationStatistics")
    @ResponseBody
    public Object populationStatistics(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                       @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                       @RequestParam(name = "year", required = false) String year,
                                       @RequestParam(name = "country", required = false) String country,
                                       @RequestParam(name = "village", required = false) String village,
                                       @RequestParam(name = "poverty", required = false) String poverty, HttpSession session,
                                       HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager page = poorFamilyService.populationStatistics(user, pageNo, pageSize, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, page);
    }

    /**
     * 贫困户人口规模统计excel导出
     *
     * @return
     */
    @OperationLog(desc = "贫困户人口规模统计excel导出", module = "统计分析")
    @RequestMapping("/exportPopulationStatistics")
    @ResponseBody
    public Object exportPopulationStatistics(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                             @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                             @RequestParam(name = "year", required = false) String year,
                                             @RequestParam(name = "country", required = false) String country,
                                             @RequestParam(name = "village", required = false) String village,
                                             @RequestParam(name = "poverty", required = false) String poverty, HttpSession session,
                                             HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {
            HSSFWorkbook wb = poorFamilyService.exportPopulationStatistics(user, pageNo, pageSize, year, country,
                    village, poverty);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户人口规模统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困人口身体健康统计
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */

    @SuppressWarnings("rawtypes")
    @OperationLog(desc = "贫困人口身体健康统计", module = "统计分析")
    @RequestMapping("/popuHealthyStatis")
    @ResponseBody
    public Object popuHealthyStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                    String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.popuHealthyStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困人口身体健康统计
     */
    @OperationLog(desc = "导出贫困人口身体健康统计", module = "统计分析")
    @RequestMapping(value = "/exportPopuHealthyStatis")
    @ResponseBody
    public Object exportPopuHealthyStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                          String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportPopuHealthyStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口身体健康情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困人口文化程度情况统计
     *
     * @param year
     * @param country
     * @param village
     * @param poverty
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困人口文化程度情况统计", module = "统计分析")
    @SuppressWarnings("rawtypes")
    @RequestMapping("/popuCultureStatis")
    @ResponseBody
    public Object popuCultureStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                    String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.popuCultureStatisPager(pageNo, pageSize, user, year, country, village, poverty);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困人口文化程度统计表
     */
    @OperationLog(desc = "导出贫困人口文化程度统计", module = "统计分析")
    @RequestMapping(value = "/exportPopuCultureStatis")
    @ResponseBody
    public Object exportPopuCultureStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                          String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {
            HSSFWorkbook wb = familyService.exportPopuCultureStatis(user, pageNo, pageSize, year, country, village,
                    poverty);


            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困人口文化程度情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户党员情况统计
     *
     * @return
     */
    @OperationLog(desc = "贫困户党员情况统计", module = "统计分析")
    @RequestMapping("/CPCStatistics")
    @ResponseBody
    public Object CPCStatistics(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                @RequestParam(name = "year", required = false) String year,
                                @RequestParam(name = "country", required = false) String country,
                                @RequestParam(name = "village", required = false) String village,
                                @RequestParam(name = "poverty", required = false) String poverty, HttpSession session,
                                HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager page = poorFamilyService.CPCStatistics(user, pageNo, pageSize, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, page);
    }

    /**
     * 贫困户党员情况统计excel导出
     *
     * @return
     */
    @OperationLog(desc = "贫困户党员情况统计excel导出", module = "统计分析")
    @RequestMapping("/exportCPCStatistics")
    @ResponseBody
    public Object exportCPCStatistics(@RequestParam(name = "pageNo", required = false) Integer pageNo,
                                      @RequestParam(name = "pageSize", required = false) Integer pageSize,
                                      @RequestParam(name = "year", required = false) String year,
                                      @RequestParam(name = "country", required = false) String country,
                                      @RequestParam(name = "village", required = false) String village,
                                      @RequestParam(name = "poverty", required = false) String poverty, HttpSession session,
                                      HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {
            HSSFWorkbook wb = poorFamilyService.exportCPCStatistics(user, pageNo, pageSize, year, country, village,
                    poverty);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户党员情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户生产生活条件困难情况统计
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户生产生活条件困难情况统计", module = "统计分析")
    @RequestMapping("/ductionLifeStatis")
    @ResponseBody
    public Object ductionLifeStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                    String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.ductionLifeStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户生产生活条件困难情况统计
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户生产生活条件困难情况统计", module = "统计分析")
    @RequestMapping(value = "/exportDuctionLifeStatis")
    @ResponseBody
    public Object exportDuctionLifeStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                          String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportDuctionLifeStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户生产生活条件困难情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户土地资源情况统计
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户土地资源情况统计", module = "统计分析")
    @RequestMapping("/landResourceStatis")
    @ResponseBody
    public Object landResourceStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                     String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.landResourceStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户土地资源情况统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户土地资源情况统计", module = "统计分析")
    @RequestMapping(value = "/exportLandResourceStatis")
    @ResponseBody
    public Object exportLandResourceStatis(Integer pageNo, Integer pageSize, String year, String poverty,
                                           String country, String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportLandResourceStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户土地资源情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户人均收入分组情况统计
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户人均收入分组情况统计", module = "统计分析")
    @RequestMapping("/capitaIncomeStatis")
    @ResponseBody
    public Object capitaIncomeStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                     String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.capitaIncomeStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户人均收入分组情况统计
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户人均收入分组情况统计", module = "统计分析")
    @RequestMapping(value = "/exportCapitaIncomeStatis")
    @ResponseBody
    public Object exportCapitaIncomeStatis(Integer pageNo, Integer pageSize, String year, String poverty,
                                           String country, String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportCapitaIncomeStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户人均收入分组情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户主要燃料分类统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户主要燃料分类统计", module = "统计分析")
    @RequestMapping("/fuelTypeStatis")
    @ResponseBody
    public Object fuelTypeStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                 String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.fuelTypeStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户主要燃料分类统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户主要燃料分类统计", module = "统计分析")
    @RequestMapping(value = "/exportFuelTypeStatis")
    @ResponseBody
    public Object exportFuelTypeStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                       String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportFuelTypeStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户主要燃料分类统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户入户路情况分类统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户入户路情况分类统计", module = "统计分析")
    @RequestMapping("/entranceRoadStatis")
    @ResponseBody
    public Object entranceRoadStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                     String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.entranceRoadStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户入户路情况分类统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户入户路情况分类统计", module = "统计分析")
    @RequestMapping(value = "/exportEntranceRoadStatis")
    @ResponseBody
    public Object exportEntranceRoadStatis(Integer pageNo, Integer pageSize, String year, String poverty,
                                           String country, String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportEntranceRoadStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户入户路情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户家庭收入情况统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户家庭收入情况统计", module = "统计分析")
    @RequestMapping("/familyIncomeStatis")
    @ResponseBody
    public Object familyIncomeStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                     String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.familyIncomeStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户家庭收入情况统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户家庭收入情况统计", module = "统计分析")
    @RequestMapping(value = "/exportFamilyIncomeStatis")
    @ResponseBody
    public Object exportFamilyIncomeStatis(Integer pageNo, Integer pageSize, String year, String poverty,
                                           String country, String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportFamilyIncomeStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户家庭收入情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 贫困户转移性收入构成情况统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "贫困户转移性收入构成情况统计", module = "统计分析")
    @RequestMapping("/transferableIncStatis")
    @ResponseBody
    public Object transferableIncStatis(Integer pageNo, Integer pageSize, String year, String poverty, String country,
                                        String village, HttpSession session, HttpServletResponse response) {
        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        Pager list = familyService.transferableIncStatisPager(pageNo, pageSize, user, year, country, village, poverty);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 导出贫困户转移性收入构成情况统计表
     *
     * @param year     业务年度
     * @param country  乡
     * @param village  村
     * @param poverty  变更类型
     * @param session
     * @param response
     * @return
     */
    @OperationLog(desc = "导出贫困户转移性收入构成情况统计", module = "统计分析")
    @RequestMapping(value = "/exportTransferableIncStatis")
    @ResponseBody
    public Object exportTransferableIncStatis(Integer pageNo, Integer pageSize, String year, String poverty,
                                              String country, String village, HttpSession session, HttpServletResponse response) {

        pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        try {

            HSSFWorkbook wb = familyService.exportTransferableIncStatis(user, pageNo, pageSize, year, poverty, country,
                    village);

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户转移性收入构成情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 根据多个id查询家庭成员
     */
    @RequestMapping("/findFamily")
    @ResponseBody
    public Object findFamily(HttpServletRequest request) {
        String sid = request.getParameter("sid");
        if (org.apache.commons.lang.StringUtils.isBlank(sid)) {
            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS);
        }
        String[] spli = sid.split(",");
        Family family = null;
        ArrayList arrayList = new ArrayList<>();
        for (int i = 0; i < spli.length; i++) {
            family = familyService.retrieveObject((Long.valueOf(spli[i])));
            arrayList.add(family);
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, arrayList);
    }

    /**
     * 贫困户帮扶责任人落实情况统计表
     */
    @OperationLog(desc = "贫困户帮扶责任人落实情况统计表查询", module = "统计分析")
    @RequestMapping("/findFamilyLiable")
    @ResponseBody
    public Object findFamilyLiable(Integer pageNo, Integer pageSize,
                                   @RequestParam(name = "year", required = false) String year,
                                   @RequestParam(name = "country", required = false) String country,
                                   @RequestParam(name = "village", required = false) String village,
                                   @RequestParam(name = "type", required = false) String type, HttpSession session) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        Pager list = poorFamilyService.findFamilyLiable(user, pageNo, pageSize, year, country, village, type);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, list);
    }

    /**
     * 贫困户帮扶责任人落实情况统计表excel导出
     */
    @OperationLog(desc = "贫困户帮扶责任人落实情况统计表导出", module = "统计分析")
    @RequestMapping("/exportFindFamilyLiable")
    @ResponseBody
    public Object exportFindFamilyLiable(@RequestParam(name = "year", required = false) String year,
                                         @RequestParam(name = "country", required = false) String country,
                                         @RequestParam(name = "village", required = false) String village,
                                         @RequestParam(name = "type", required = false) String type, HttpSession session,
                                         HttpServletResponse response) {

        McUser user = userService
                .retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        HSSFWorkbook wb = poorFamilyService.exportFindFamilyLiable(user, null, null, year, country, village, type);
        try {

            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("贫困户帮扶责任人落实情况统计表", "UTF-8") + ".xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(bufferedOutputStream);
            bufferedOutputStream.close();

            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
        }
    }

    /**
     * 身份证读卡功能
     *
     * @throws ParseException
     */
    @OperationLog(desc = "身份证读卡", module = "扶贫对象管理")
    @RequestMapping("/IDcard")
    @ResponseBody
    @Deprecated
    public Object IDcard(Long sid, HttpServletRequest request) {
        String birthTime = request.getParameter("birthTime") + " ";
        String idNumber = request.getParameter("idNumber");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        Family family = familyService.familyBuId(sid);
        String sexF = StringUtil.isBlank(family.getSex()) ? "0" : family.getSex();
        String nameF = StringUtil.isBlank(family.getName()) ? "0" : family.getName();
        String idNumberF = StringUtil.isBlank(family.getIdNumber()) ? "0" : family.getIdNumber();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
        String birthTimeF;
        if (family.getBirthTime() != null) {
            birthTimeF = family.getBirthTime().toString().substring(0, 11);
        } else {
            birthTimeF = "0";
        }

        if (nameF.equals(name) && birthTime.equals(birthTimeF) && idNumberF.equals(idNumber) && sexF.equals(sex)) {
            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "身份信息核对一致！");
        } else {
//			Family family0 = this.familyService.getFamily1(family);
//			family0.setName(name);
//			Date aaa;
//			try {
//				aaa = sdf.parse(birthTime);
//				family0.setBirthTime(aaa);
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//			family0.setIdNumber(idNumber);
//			family0.setSex(sex);
//			this.familyService.modifyObject2(family0);
            return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "身份信息核对不一致，系统将会自动修正数据！");
        }

    }


    /**
     * 查找指定的贫困户变更历史
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/getPoorFamilyHistory")
    @ResponseBody
    public Object getPoorFamilyHistory(@RequestParam(name = "id") Long id, HttpSession session) {
        McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
        PoorFamilyHistory poorFamilyHistory = poorFamilyService.getPoorFamilyHistory(id);
        PoorFamily poorFamily = this.poorFamilyService.get(poorFamilyHistory.getOriginId());

        List<HelpPerson> helpPerson = new ArrayList<>();
        if (poorFamily != null) {
            Iterator<HelpPerson> it = poorFamily.getHelpPersons().iterator();
            while (it.hasNext()) {
                HelpPerson next = it.next();
                if ("1".equalsIgnoreCase(next.getStatus())) helpPerson.add(next);
            }
        }

        PoorFamily tempPoorFamily = new PoorFamily();
        BeanUtils.copyProperties(poorFamilyHistory, tempPoorFamily);
        tempPoorFamily.setHelpPersons(helpPerson);

        List<Family> familys = new ArrayList<>();
        for (FamilyHistory fh : poorFamilyHistory.getFamilyHistories()) {
            Family family = new Family();
            BeanUtils.copyProperties(fh, family);
            familys.add(family);
        }

        tempPoorFamily.setFamily(familys);
        Map map = new HashMap<>();
        map.put("poorFamily", tempPoorFamily);

        Map<String, Object> fieldPermission = new HashMap<>();

        Permission poorFamilyManagementPermission = permissionService.getPermissionByURI("povertyStrickenMng");
        if (poorFamilyManagementPermission != null) {
            for (Role r : user.getRoles()) {
                for (Permission e : r.getPermissions()) {
                    if (e.getPermissionId() == poorFamilyManagementPermission.getId()) {
                        fieldPermission.put(e.getName(), true);
                    }
                }
            }
        }
        map.put("fieldPermission", fieldPermission);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, map);

    }

    /**
     * 生成家庭成员变更记录
     *
     * @param family
     * @return
     */
    private FamilyHistory generateFamilyHistory(Family family) {
        FamilyHistory familyHistory = new FamilyHistory();
        BeanUtils.copyProperties(family, familyHistory);
        familyHistory.setId(null);
        familyHistory.setOriginId(family.getId());
        return familyHistory;
    }

    /**
     * 生成贫困户变更记录
     *
     * @param
     * @return
     */
    private PoorFamilyHistory generatePoorFamilyHistory(PoorFamily poorFamily) {
        PoorFamilyHistory poorFamilyHistory = new PoorFamilyHistory();
        BeanUtils.copyProperties(poorFamily, poorFamilyHistory);
        poorFamilyHistory.setId(null);
        poorFamilyHistory.setOriginId(poorFamily.getId());
        return poorFamilyHistory;
    }


    /**
     * 贫困户照片资料上传
     */
    @RequestMapping(value="/poorFamilyImgUpload", method = RequestMethod.POST)
    public ResponseEntity<Map<String, String>> poorFamilyImgUpload(
            @RequestParam(name = "img") MultipartFile img,
            HttpSession session ) throws IOException {
        McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);

        //处理文件上传
        StringBuilder url = new StringBuilder("");
        String realPath = session.getServletContext().getRealPath("/" + imgPath);
        if (img.isEmpty()) {
            log.warn("文件未上传");
            return new ResponseEntity<>(null, headers, HttpStatus.BAD_REQUEST);
        } else {
            String fileName = img.getOriginalFilename();
            String baseName = FilenameUtils.getBaseName(fileName);
            if (baseName.length() > 50)
                return new ResponseEntity<>(Collections.<String, String>generateHashMap("status","405","message","文件名过长"), headers, HttpStatus.BAD_REQUEST);
            String extension = FilenameUtils.getExtension(fileName);

            fileName = user.getId() + "_" + System.currentTimeMillis() + "_" + baseName + "." + extension;

            url.append(imgPath + "/" + fileName);
            //old
            //FileUtils.copyInputStreamToFile(img.getInputStream(), new File(realPath, fileName));
            //生成空的文件
            //FileUtils.touch( new File(realPath, fileName));
            //FileUtils.copyInputStreamToFile(request.getInputStream(), new File(realPath, fileName));
            //压缩图片
            //ImageHelper.compress(img.getInputStream(), new File(realPath, fileName), 1);
            /* 其中的scale是可以指定图片的大小，值在0到1之间，1f就是原图大小，0.5就是原图的一半大小，这里的大小是指图片的长宽。
				而outputQuality是图片的质量，值也是在0到1，越接近于1质量越好，越接近于0质量越差。*/
            
            //FileUtils.copyInputStreamToFile(img.getInputStream(), new File(realPath, fileName));
            //Thumbnails.of(realPath+File.separator+fileName).scale(1f).outputQuality(0.75f).toFile(realPath+File.separator+fileName);
            FileUtils.touch(new File(realPath, fileName));
            Thumbnails.of(img.getInputStream()).scale(1D).outputQuality(0.7D).toFile(realPath+File.separator+fileName);      
            return new ResponseEntity<>(
                    Collections.<String, String>generateHashMap("status","200","url",url.toString(),"filename", baseName + "." + extension), headers, HttpStatus.OK);
        }
    }

    /**
     * 贫困户照片资料更新(删除)
     */
    private void updatePoorFamilyImgs(PoorFamily persistentPoorFamily, PoorFamily poorFamily) {
        List<String> changedImgs = new ArrayList<>();

        //申请对象
        String persistentPoorFamilyReliefObjImg = persistentPoorFamily.getReliefObjImg();
        String poorFamilyReliefObjImg = poorFamily.getReliefObjImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyReliefObjImg, poorFamilyReliefObjImg);

        //申请时间
        String persistentPoorFamilyApplicationTimeImg = persistentPoorFamily.getApplicationTimeImg();
        String poorFamilyApplicationTimeImg = poorFamily.getApplicationTimeImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyApplicationTimeImg, poorFamilyApplicationTimeImg);

        //查勘结果内容照片
        String persistentPoorFamilyResultContentImg = persistentPoorFamily.getResultContentImg();
        String poorFamilyResultContentImg = poorFamily.getResultContentImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyResultContentImg, poorFamilyResultContentImg);

        // 评议照片
        String persistentPoorFamilyEvaluationImg = persistentPoorFamily.getEvaluationTimeImg();
        String poorFamilyEvaluationImg = poorFamily.getEvaluationTimeImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyEvaluationImg, poorFamilyEvaluationImg);

        // 公示照片
        String persistentPoorFamilyPublicationImg = persistentPoorFamily.getPublicationTimeImg();
        String poorFamilyPublicationImg = poorFamily.getPublicationTimeImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyPublicationImg, poorFamilyPublicationImg);

        // 因灾损失金额照片
        String persistentPoorFamilyCalamityImg = persistentPoorFamily.getCalamityImg();
        String poorFamilyCalamityImg = poorFamily.getCalamityImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyCalamityImg, poorFamilyCalamityImg);

        // 因学学费金额照片
        String persistentPoorFamilyEducationImg = persistentPoorFamily.getEducationImg();
        String poorFamilyEducationImg = poorFamily.getEducationImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyEducationImg, poorFamilyEducationImg);

        // 因病自费金额照片
        String persistentPoorFamilyIllnessImg = persistentPoorFamily.getIllnessImg();
        String poorFamilyIllnessImg = poorFamily.getIllnessImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyIllnessImg, poorFamilyIllnessImg);

        // 救助金额照片
        String persistentPoorFamilyReliefAmoImg = persistentPoorFamily.getReliefAmoImg();
        String poorFamilyReliefAmoImg = poorFamily.getReliefAmoImg();
        peekInvalidFile(changedImgs, persistentPoorFamilyReliefAmoImg, poorFamilyReliefAmoImg);

        //TODO 照片删除

    }

    /**
     * 筛选无用文件
     */
    private void peekInvalidFile(List<String> result, String oldName, String newName) {
        if (StringUtils.isNotBlank(oldName)
                && !oldName.equals(newName)) {
            result.add(oldName);
        }
    }
    
    /** 根据村id查找所有贫困户 的 信息*/
//    public Object findPoorFamilyByVillageId(@RequestParam(required=true,name="villageId")  Long villageId){
//    	 //List<Family> familyList = this.familyService.queryFaAll();
//    	 List result =  this.poorFamilyService.findPoorFamilyByVillageId(villageId);
//    	 
//         return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, result);
//    }
    
   /**
    * 根据条件查询贫困户 
    * @param pageNo
    * @param pageSize
    * @param country   乡
    * @param village   村
    * @param poorName  家庭成员名字
    * @param poorFamilyNum   户编号
    * @return
    */
    @RequestMapping(method=RequestMethod.GET,value="/findPoorFamilyByCondition")
    @ResponseBody
    public Object findPoorFamilyByCondition(@RequestParam(value="pageNo",required=false,defaultValue="1")Integer pageNo, @RequestParam(value="pageSize",required=false,defaultValue="10")Integer pageSize,
    		@RequestParam(value="country",required=false)String country ,@RequestParam(value="village",required=false) String village ,@RequestParam(value="poorName",required=false)String poorName ,@RequestParam(value="poorFamilyNum",required=false)String poorFamilyNum ){
    	
    	Pager pager = this.poorFamilyService.findPoorFamilyByCondition(pageNo,pageSize,country,village,poorName,poorFamilyNum);
    	
    	return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }
    
   
}
